using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace Blimpbots.Recognition.Euclidian
{
    public class Rectangles
    {
        public static Rectangle[] Merge(Rectangle[] rectangleSet)
        {
            LinkedList<Rectangle> rectangleList = new LinkedList<Rectangle>(rectangleSet);
            return Merge(rectangleList);
        }
        public static Rectangle[] Merge(LinkedList<Rectangle> rectangleSet)
        {
            LinkedListNode<Rectangle> nodeA = rectangleSet.First;
            LinkedListNode<Rectangle> nodeB;

            while (nodeA != null)
            {
                Rectangle r = nodeA.Value;
                nodeB = nodeA.Next;

                if (nodeB == null) nodeB = rectangleSet.First; // wrap around
                while (nodeB != nodeA)
                {
                    if (r.IntersectsWith(nodeB.Value))
                    {
                        r = Merge(r, nodeB.Value);
                        LinkedListNode<Rectangle> toDelete = nodeB;
                        nodeB = nodeB.Next;
                        rectangleSet.Remove(toDelete);
                    }
                    else
                        nodeB = nodeB.Next;

                    // Wrap around
                    if (nodeB == null)
                        nodeB = rectangleSet.First;
                }

                nodeA.Value = r;

                nodeA = nodeA.Next;
            }

            nodeA = rectangleSet.First;
            Rectangle[] objectRectArr = new Rectangle[rectangleSet.Count];
            for (int i = 0; i < rectangleSet.Count; i++)
            {
                objectRectArr[i] = nodeA.Value;
                nodeA = nodeA.Next;
            }
            return objectRectArr;
        }
        public static Rectangle Merge(Rectangle A, Rectangle B)
        {
            int min_x, min_y, max_x, max_y;
            min_x = Math.Min(A.Left, B.Left);
            min_y = Math.Min(A.Top, B.Top);
            max_x = Math.Max(A.Right, B.Right);
            max_y = Math.Max(A.Bottom, B.Bottom);
            return new Rectangle(min_x, min_y, max_x - min_x, max_y - min_y);
        }
    }
}
